package com.chj.utils;

import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;

public class PulsarUtil {

    private static PulsarUtil pulsarUtil = new PulsarUtil();
    PulsarClient client = null;
    Producer<byte[]> producer = null;


    private PulsarUtil() {
        try {
            client = PulsarClient.builder().serviceUrl("pulsar://192.168.2.180:26650").build();
            producer = client.newProducer().producerName("producer-test")
                    .topic("persistent://sample/standalone/ns1/my-topic")
                    .create();
        } catch (PulsarClientException e) {
            e.printStackTrace();
        }
    }

    public static PulsarUtil getInstance() {
        if (pulsarUtil == null) {
            pulsarUtil = new PulsarUtil();
        }
        return pulsarUtil;
    }

    public String sendMQMsg(String message) {
        try {
            MessageId messageId = producer.send(message.getBytes());
            return messageId == null ? "null" : messageId.toString();
        } catch (PulsarClientException e) {
            e.printStackTrace();
        }
        return null;
    }

}
